import { InjectionKey } from 'vue'

import { useStore as baseUseStore, createStore, Store } from 'vuex'

interface State {
    count: number
    username: string
    currentMenu: string // 当前菜单
}

export const key: InjectionKey<Store<State>> = Symbol()

export const store = createStore<State>({
    state: {
        count: 0,
        username: 'zhangsan',
        currentMenu: localStorage.getItem('currentMenu') || '1',
    },
    getters: {
        getName: (state: State) => {
            return state.username
        },
        getCurrentMenu: (state: State) => {
            return state.currentMenu
        },
        getCount: (state: State) => {
            return state.count
        },
    },
    mutations: {
        SET_USERNAME(state: State, username: string) {
            state.username = username
        },
        SET_CURRENT_MENU(state: State, currentMenu: string) {
            localStorage.setItem('currentMenu', currentMenu)
            state.currentMenu = currentMenu
        },
        addCount: (state: State, count: number) => {
            state.count = count
        },
    },
    actions: {
        setCurrentMenu({ commit }, currentMenu: string) {
            commit('SET_CURRENT_MENU', currentMenu)
        },
    },
})

// 定义自己的`useStore`组合函数
export function useStore() {
    return baseUseStore(key)
}
